package cn.kgb.util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kgb.dao.LoginDAO;
import cn.kgb.javabean.User;

public class ForceLoginFilter implements Filter {

	
	/**
     * Default constructor. 
     */
    public ForceLoginFilter() {
    }
    
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filter) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		System.out.println("ip:"+httpRequest.getRemoteAddr() + "  time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()));
		User sessionLoginId = (User) httpRequest.getSession().getAttribute("user");
		if(sessionLoginId == null ){
			
			Cookie[] cookieList = httpRequest.getCookies();
			if(cookieList == null) {
				filter.doFilter(request, response);
				return;
			}
			int length = cookieList.length;
			boolean auto = false;
			for(int i=0;i<length;i++){
				
				if(cookieList[i].getName().equals("hDMDWl0g")){
					String cookieStr  = cookieList[i].getValue();
				
					if(cookieStr != null && cookieStr.indexOf(",") != -1){
						String[] values = cookieStr.split(",");
						if(values.length == 2){
							LoginDAO Ld = new LoginDAO();
							User puser= Ld.logIn(values[0], values[1]);
							if(puser != null){
								httpRequest.getSession().setAttribute("user", puser);
								httpRequest.getRequestDispatcher("/frame/AdminIndex.jsp").forward(request, response);
							}else{
								auto = false;
								break;
							}
						}
						auto = false;
						break;
					}
					
				}
			}
			if(!auto){
				filter.doFilter(request, response);
			}
		}else{
			
			
			filter.doFilter(request, response);
		}
		
		
	}
	
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
